package servlet.man;

import bean.Result;
import bean.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 李夏
 * @version 1.0
 */
//按照学生id或学生名字模糊查询
@WebServlet("/man/getStuIdName")
public class GetStuIdNameServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer stuId = null;
        if (Integer.valueOf(request.getParameter("stuId")) != 0) {
            stuId = Integer.valueOf(request.getParameter("stuId"));

        }
        String stuName = request.getParameter("stuName");
        List<Student> studentList = null;
        try {
            studentList = UserDaoImpl.getStuIdName(stuName, stuId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        Result result = new Result();
        if (studentList != null) {
            result.success(studentList);
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);


        } else {
            result.fail();
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);


        }
    }
}
